import re
import requests
from bs4 import BeautifulSoup
import uuid
import subprocess

headers = {
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36",
    "referer": "https://www.bilibili.com/"
}

url = "https://www.bilibili.com/video/BV1nRoXYKEbp/?spm_id_from=333.1007.tianma.3-2-6.click&vd_source=ad7cdb3b6b8f60928739aa4b3f8b4780"

def save_download(http_response,file_name,tooltip=""):
    count=int(http_response.headers['content-length'])
    current_count=0
    with open(f"{file_name}.m4s", "wb") as file:
        for chunk in http_response.iter_content(1024):
            current_count+=len(chunk)
            file.write(chunk)
            print(f"{tooltip}总大小：{count},已下载大小：{current_count}")

filename=uuid.uuid4().hex

response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.content, "lxml")
data = soup.find_all('script')[3]

# 视频下载
video_url=re.search(r'"baseUrl":"(.*?)"',str(data)).group(1);
video_response = requests.get(video_url)
video_path=f"videos/{filename}-video"
save_download(video_response,video_path,"视频下载中....")

# 音频下载
audio_urls=re.findall(r'"base_url":"(.*?)"',str(data));
audio_url=audio_urls[len(audio_urls)-1]
audio_path=f"videos/{filename}-audio"
audio_response = requests.get(audio_url)
save_download(audio_response,audio_path,"音频下载中....")

# 格式转换
def convert_m4s_to_mp4(vpath, apath):
    command = f"ffmpeg -i {vpath} -i {apath} -codec copy videos/converted.mp4"
    subprocess.run(command, shell=True)

convert_m4s_to_mp4(f"{video_path}.m4s",f"{audio_path}.m4s")
